package com.example.kotlintest.chat.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.kotlintest.R;
import com.example.kotlintest.chat.EmojiUtils;
import com.example.kotlintest.chat.MsgEntity;
import com.guoxiaoxing.phoenix.picker.util.DpUtils;
import com.guoxiaoxing.phoenix.picker.util.ScreenUtil;

import org.w3c.dom.Text;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author linzi
 * @date 2022-9-28
 * 消息适配器
 */
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageHodler> {
    private String minePhone="10001";
    private List<MsgEntity> msgEntityList = new ArrayList<>(Arrays.asList(
            new MsgEntity(MsgEntity.MSG_TYPE_TXT,minePhone,"10002","你想干嘛？","2022-09-20 11:30:00"),
            new MsgEntity(MsgEntity.MSG_TYPE_IMG,"10002","10001","","2022-09-21 11:30:00"),
            new MsgEntity(MsgEntity.MSG_TYPE_IMG,minePhone,"10002","","2022-09-22 11:30:00"),
            new MsgEntity(MsgEntity.MSG_TYPE_TXT,"10002",minePhone,"你想干嘛2222？","2022-09-23 11:30:00"),
            new MsgEntity(MsgEntity.MSG_TYPE_TXT,minePhone,"10002","你想干嘛333333333333？","2022-09-24 11:30:00")
    ));
    private Context context;
    private OnItemClickListener onItemClickListener;
    private RecyclerView recyclerView;

    public static MessageAdapter init(RecyclerView recycle,Context context,OnItemClickListener onItemClickListener){
        MessageAdapter adapter=new MessageAdapter(recycle,context,onItemClickListener);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(context);
        recycle.setLayoutManager(linearLayoutManager);
        recycle.setAdapter(adapter);
        return adapter;
    }

    public MsgEntity getData(int position){
        return msgEntityList.get(position);
    }
    public int getSize(){
        return msgEntityList.size();
    }
    public void addMsg(MsgEntity msg){
        msgEntityList.add(msg);
        this.notifyItemInserted(msgEntityList.size()-1);
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                recyclerView.scrollToPosition(msgEntityList.size()-1);
            }
        });
    }

    private MessageAdapter(RecyclerView recyclerView,Context context,OnItemClickListener onItemClickListener) {
        this.context = context;
        this.onItemClickListener=onItemClickListener;
        this.recyclerView=recyclerView;
    }

    @NonNull
    @Override
    public MessageHodler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(context).inflate(R.layout.chat_item_layout,parent,false);
        return new MessageHodler(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MessageHodler holder, @SuppressLint("RecyclerView") int position) {
        MsgEntity msg=msgEntityList.get(position);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        holder.tvTime.setVisibility(View.GONE);
        if(position==0){
            holder.tvTime.setVisibility(View.VISIBLE);
            holder.tvTime.setText(msg.getSendTime());
        }else {
            try {
                Date msgTime = sdf.parse(msg.getSendTime());
                MsgEntity lastMsg=msgEntityList.get(position-1);
                Date lastTime = sdf.parse(lastMsg.getSendTime());
                if (msgTime.getTime()-lastTime.getTime() > 30 * 60 * 1000) {
                    holder.tvTime.setVisibility(View.VISIBLE);
                    holder.tvTime.setText(msg.getSendTime());
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        switch (msg.getMsgType()){
            case MsgEntity.MSG_TYPE_TXT:
                if(!minePhone.equals(msg.getMsgOwer())){
                    holder.llLeft.setVisibility(View.VISIBLE);
                    holder.llRight.setVisibility(View.GONE);
                    holder.tvContent.setVisibility(View.VISIBLE);
                    holder.ivContent.setVisibility(View.GONE);
                    holder.tvVoiceLength.setVisibility(View.GONE);
                    holder.tvVoiceLengthRight.setVisibility(View.GONE);
                    holder.tvContent.setText(EmojiUtils.getMask(context,msg.getContent()));
                }else{
                    holder.llLeft.setVisibility(View.GONE);
                    holder.llRight.setVisibility(View.VISIBLE);
                    holder.tvContentRight.setVisibility(View.VISIBLE);
                    holder.ivContentRight.setVisibility(View.GONE);
                    holder.ivVoice.setVisibility(View.GONE);
                    holder.tvVoiceLength.setVisibility(View.GONE);
                    holder.tvVoiceLengthRight.setVisibility(View.GONE);
                    holder.tvContentRight.setText(EmojiUtils.getMask(context,msg.getContent()));
                }
                break;
            case MsgEntity.MSG_TYPE_IMG:
                if(!minePhone.equals(msg.getMsgOwer())){
                    holder.llLeft.setVisibility(View.VISIBLE);
                    holder.llRight.setVisibility(View.GONE);
                    holder.tvContent.setVisibility(View.GONE);
                    holder.ivContent.setVisibility(View.VISIBLE);
                    holder.tvVoiceLength.setVisibility(View.GONE);
                    holder.tvVoiceLengthRight.setVisibility(View.GONE);
                    if(!TextUtils.isEmpty(msg.getContent())){
                        holder.ivContent.setImageBitmap(EmojiUtils.getFile(msg.getContent()));
                    }else{
                        holder.ivContent.setImageBitmap(EmojiUtils.getFile(context,R.drawable.img));
                    }
                }else{
                    holder.llLeft.setVisibility(View.GONE);
                    holder.llRight.setVisibility(View.VISIBLE);
                    holder.tvContentRight.setVisibility(View.GONE);
                    holder.ivContentRight.setVisibility(View.VISIBLE);
                    holder.ivVoice.setVisibility(View.GONE);
                    holder.tvVoiceLength.setVisibility(View.GONE);
                    holder.tvVoiceLengthRight.setVisibility(View.GONE);
                    if(!TextUtils.isEmpty(msg.getContent())){
                        holder.ivContentRight.setImageBitmap(EmojiUtils.getFile(msg.getContent()));
                    }else{
                        holder.ivContentRight.setImageBitmap(EmojiUtils.getFile(context,R.drawable.img));
                    }
                }
                break;
            case MsgEntity.MSG_TYPE_AUDIO:
                //获取设置聊天气泡那个背景图的view
                RelativeLayout view;
                TextView tvLength;
                if(!minePhone.equals(msg.getMsgOwer())){
                    view=holder.rlContent;
                    holder.llLeft.setVisibility(View.VISIBLE);
                    holder.llRight.setVisibility(View.GONE);
                    holder.tvContent.setVisibility(View.GONE);
                    holder.ivContent.setVisibility(View.GONE);
                    holder.ivVoiceLeft.setVisibility(View.VISIBLE);
                    holder.ivVoice.setVisibility(View.GONE);
                    holder.tvVoiceLength.setVisibility(View.VISIBLE);
                    holder.tvVoiceLengthRight.setVisibility(View.GONE);
                    tvLength=holder.tvVoiceLength;
                }else{
                    view=holder.rlContentRight;
                    holder.llLeft.setVisibility(View.GONE);
                    holder.llRight.setVisibility(View.VISIBLE);
                    holder.tvContentRight.setVisibility(View.GONE);
                    holder.ivContentRight.setVisibility(View.GONE);
                    holder.ivVoiceLeft.setVisibility(View.GONE);
                    holder.ivVoice.setVisibility(View.VISIBLE);
                    holder.tvVoiceLength.setVisibility(View.GONE);
                    holder.tvVoiceLengthRight.setVisibility(View.VISIBLE);
                    tvLength=holder.tvVoiceLengthRight;
                }
                resizeAudioView(view,tvLength,msg.getContent());
                break;
        }
        holder.ivVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onItemClickListener.itemClick(holder, position);
            }
        });
        holder.ivVoiceLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onItemClickListener.itemClick(holder, position);
            }
        });
    }

    /***
     * 根据语音时长动态设置长度
     * @param view 放通话气泡背景那个view控件
     * @param audioPath 音频文件缓存路径
     */
    private void resizeAudioView(View view,TextView lenght,String audioPath){
        //进度换算最大时长，因为显示宽度有一个最大宽度，所以需要此值进行换算；值越大，宽度显示变换就越小，暂定60s，超过这个时长之后就显示最大宽度
        int maxTime=60;
        int minTime=2;
        //最小宽度【建议设置为头像宽度】
        int maxWidth = (int) (ScreenUtil.INSTANCE.getScreenWidth(context)*0.6f);
        int minWidth = DpUtils.INSTANCE.dp2px(60,context);
        view.post(new Runnable() {
            @Override
            public void run() {
                //获取音频文件时长，因为宽度是有限制的，所以音频需要有一个用以判断的临界值
                long time=0;
                try {
                    MediaPlayer player = new MediaPlayer();
                    player.setDataSource(audioPath);
                    player.prepare();

                    time=player.getDuration();
                    player.reset();
                    player.release();
                    Log.e(TAG, "run: time="+time );
                    //从毫秒换算为秒
                    time=time/1000;
                }catch (Exception e){
                    e.printStackTrace();
                }
                int widthChange = maxWidth-minWidth;
                //获取控件本身LP
                ViewGroup.LayoutParams layoutParams= view.getLayoutParams();
                int width=0;
                if(time>=maxTime){
                    width= maxWidth;
                }else {
                    if(time<=minTime){
                        width=minWidth;
                    }else {
                        int vTime = (int) (time%10);
                        if(time>=50){
                            width = (int) (minWidth +(widthChange*0.9f)+(vTime/10f) * widthChange*0.1);
                        }else if(time>=40&&time<50){
                            width = (int) (minWidth +(widthChange*0.8f)+(vTime/10f) * widthChange*0.1);
                        }else if(time>=30&&time<40){
                            width = (int) (minWidth +(widthChange*0.65f)+(vTime/10f) * widthChange*0.15);
                        }else if( time>=20&&time<30){
                            width = (int) (minWidth +(widthChange*0.5f)+(vTime/10f) * widthChange*0.15);
                        }else if(time >=10 && time<20){
                            width = (int) (minWidth +(widthChange*0.3f)+(vTime/10f) * widthChange*0.2);
                        }else{
//                            width = (int) (minWidth+0.5*widthChange+(time-10)*0.01*widthChange);
                            width = (int) (minWidth+(vTime/10f) * widthChange*0.3);
                        }
                    }
                }
                Log.e(TAG, "run: "+width );
                layoutParams.width=width;
                view.setLayoutParams(layoutParams);
                lenght.setText(time+"s");
            }
        });
    }

    private static final String TAG = "MessageAdapter";
    @Override
    public int getItemCount() {
        return msgEntityList.size();
    }

    public static class MessageHodler extends RecyclerView.ViewHolder {
        public TextView tvTime;
        public LinearLayout llRight;
        public LinearLayout llLeft;
        public RelativeLayout rlContent;
        public RelativeLayout rlContentRight;
        public ImageView ivHeadLeft;
        public ImageView ivHeadRight;
        public TextView tvContent;
        public TextView tvContentRight;
        public ImageView ivContent;
        public ImageView ivContentRight;
        public ImageView ivVoice;
        public ImageView ivVoiceLeft;
        public TextView tvVoiceLength;
        public TextView tvVoiceLengthRight;
        public MessageHodler(@NonNull View itemView) {
            super(itemView);
            llRight = itemView.findViewById(R.id.llRight);
            llLeft = itemView.findViewById(R.id.llLeft);
            tvTime = itemView.findViewById(R.id.tvTime);
            rlContent = itemView.findViewById(R.id.rlContent);
            rlContentRight = itemView.findViewById(R.id.rlContentRight);
            ivHeadLeft = itemView.findViewById(R.id.ivHeadLeft);
            ivHeadRight = itemView.findViewById(R.id.ivHeadRight);
            tvContent = itemView.findViewById(R.id.tvContent);
            tvContentRight = itemView.findViewById(R.id.tvContentRight);
            ivContent = itemView.findViewById(R.id.ivContent);
            ivContentRight = itemView.findViewById(R.id.ivContentRight);
            ivVoice = itemView.findViewById(R.id.ivVoice);
            ivVoiceLeft = itemView.findViewById(R.id.ivVoiceLeft);
            tvVoiceLength = itemView.findViewById(R.id.tvVoiceLength);
            tvVoiceLengthRight = itemView.findViewById(R.id.tvVoiceLengthRight);
        }
    }

    public interface OnItemClickListener{
        void itemClick(MessageAdapter.MessageHodler menuHolder, int postion);
    }
}
